import React from 'react';
import { Modal, Form, Input, Checkbox, message, TreeSelect, Row, Col } from 'antd';
import Api from 'Utils/api';
import './index.scss';

const FormItem = Form.Item;
const CheckboxGroup = Checkbox.Group;
const TreeNode = TreeSelect.TreeNode;
const AddForm = Form.create()(
  (props) => {
    const { form, initialValue, roleNameList, onRenderDepartmentTreeNode, selectCheckBox } = props;
    const { getFieldDecorator } = form;
    return (
      <Form className="task-form">
        <FormItem
          label="用户名:"
        >
          {
            getFieldDecorator('username', {
              initialValue: initialValue ? initialValue.username : '',
              rules: [
                { required: true, message: '请输入' }
              ]
            })(
              <Input placeholder="请输入用户名" style={{ width: 300 }} />
            )
          }
        </FormItem>
        <FormItem
          label="昵称:"
        >
          {
            getFieldDecorator('nickname', {
              initialValue: initialValue ? initialValue.nickname : '',
              rules: [
                { required: true, message: '请输入' }
              ]
            })(
              <Input placeholder="请输入昵称" style={{ width: 300 }} />
            )
          }
        </FormItem>
        <FormItem
          label="部门:"
        >
          {
            getFieldDecorator('dept', {
              initialValue: initialValue ? initialValue.dept_id.toString() : undefined,
              rules: [
                { required: true, message: '请选择' }
              ]
            })(
              <TreeSelect
                style={{ width: 300 }}
                dropdownStyle={{ maxHeight: 300, overflow: 'auto' }}
                placeholder="请选择"
              >
                {
                  onRenderDepartmentTreeNode
                }
              </TreeSelect>
            )
          }
        </FormItem>
        <FormItem >
          {
            getFieldDecorator('roles', {
              initialValue: selectCheckBox,
              rules: [
                { required: true, message: '请选择账户角色' }
              ]
            })(
              <CheckboxGroup >
                <Row>
                  {
                    roleNameList.map(item => (
                      <Col span={12} key={item.id}><Checkbox value={item.id.toString()} key={item.id}>{item.name}</Checkbox></Col>
                    ))
                  }
                </Row>
              </CheckboxGroup>
            )
          }
        </FormItem>
      </Form>
    );
  }
);
class AddModal extends React.PureComponent {
  constructor(props) {
    super(props);
    this.state = {
      visible: false,
      loading: false,
      isAdd: false,
      record: '',
      roleList: [],
      treeData: [],
      selectCheckBox: [],
    };
    this.initRoleList = ::this.initRoleList;
    this.initRenderTreeData = ::this.initRenderTreeData;
    this.initList = :: this.initList;
    this.renderDepartmentTreeNode = ::this.renderDepartmentTreeNode;
    this.renderTreeNode = ::this.renderTreeNode;
  }
  componentDidMount() {
    this.initRoleList();
    this.initRenderTreeData();
  }
  initRoleList() {
    const api = new Api({
      method: 'GET',
      path: '/roles',
      success: (json) => {
        this.setState({ roleList: json.data_list }, () => {
          this.initList();
        });
      },
      error: (msg) => {
        message.error(msg);
      }
    });
    api.run();
  }
  initRenderTreeData() {
    const api = new Api({
      method: 'GET',
      path: '/depts/admin',
      success: (json) => {
        this.setState({
          treeData: json,
        });
      },
      error: (msg) => {
        message.error(msg);
      }
    });
    api.run();
  }
  initList() {
    const newArrayRoleName = [];
    for (let i = 0; i < this.state.roleList.length; i++) {
      newArrayRoleName.push(this.state.roleList[i].name);
    }
    return newArrayRoleName;
  }
  showModal(record) {
    const self = this;
    this.setState({
      visible: true,
      record: record.id ? record : {},
      selectCheckBox: record.id ? record.roles.map(item => item.id.toString()) : []
    }, () => {
      self.form.resetFields();
    });
    if (!record.id) {
      this.setState({ isAdd: true });
    } else {
      this.setState({ isAdd: false });
    }
  }

  close() {
    this.setState({
      loading: false,
      visible: false,
    });
  }
  renderDepartmentTreeNode() {
    return this.state.treeData.map((tree) => {
      return this.renderTreeNode(tree);
    });
  }
  renderTreeNode(item) {
    if (!item.sub_depts) {
      return (
        <TreeNode value={item.id.toString()} title={item.name} key={item.id} />
      );
    }
    if (item.sub_depts.length === 0) {
      return (
        <TreeNode value={item.id.toString()} title={item.name} key={item.id} />
      );
    }
    return (
      <TreeNode value={item.id.toString()} title={item.name} key={item.id}>
        {
          item.sub_depts.map((child) => {
            return this.renderTreeNode(child);
          })
        }
      </TreeNode>
    );
  }
  handleOk() {
    const { isAdd } = this.state;
    const formValue = this.form.getFieldsValue();
    this.setState({ loading: true });
    this.form.validateFieldsAndScroll((err) => {
      if (!err) {
        const self = this;
        if (!isAdd) {
          const editApi = new Api({
            method: 'PUT',
            path: `/accounts/${this.state.record.id}`,
            data: {
              role_ids: formValue.roles.map(item => parseInt(item, 10)),
              username: formValue.username,
              dept_id: parseInt(formValue.dept, 10)
            },
            success: () => {
              self.props.onOk();
              self.close();
            },
            error: (msg) => {
              message.error(msg);
            }
          });
          editApi.run();
        } else {
          const addApi = new Api({
            method: 'POST',
            path: '/accounts',
            data: {
              role_ids: formValue.roles.map(item => parseInt(item, 10)),
              username: formValue.username,
              nickname: formValue.nickname,
              dept_id: parseInt(formValue.dept, 10)
            },
            success: () => {
              self.props.onOk();
              self.close();
            },
            error: (msg) => {
              message.error(msg);
            }
          });
          addApi.run();
        }
      }
    });
  }
  render() {
    const { record, roleList } = this.state;
    const title = this.state.isAdd ? '新增' : '修改';
    const { selectCheckBox } = this.state;
    return (
      <Modal
        title={`${title}账户`}
        visible={this.state.visible}
        width={800}
        onOk={this.handleOk.bind(this)}
        onCancel={this.close.bind(this)}
        className="add-account-modal small-modal"
        confirmLoading={this.state.loading}
      >
        <AddForm
          initialValue={record.id ? record : ''}
          selectCheckBox={selectCheckBox}
          ref={(ref) => { this.form = ref; }}
          roleNameList={roleList}
          onRenderDepartmentTreeNode={this.renderDepartmentTreeNode()}
        />
      </Modal>
    );
  }
}

export default AddModal;

